//
//  VIZUserViewAccountModel.swift
//  VIZ微博
//
//  Created by 位立志 on 16/4/10.
//  Copyright © 2016年 位立志. All rights reserved.
//

import UIKit
//import SVProgressHUD



private let userInfoKey = "userInfoKey"


class VIZUserViewAccountModel: NSObject {
    
    //单例
    static let shardInstance : VIZUserViewAccountModel = VIZUserViewAccountModel()
    
    //创建一个用户模型,保存数据
    var userInfo : VIZUserInfo?
    
    //添加一个用户头像的url属性
    var iconImageUrl : NSURL {
        let url = NSURL(string:self.userInfo?.avatar_large ?? "")
        return url!
    }
    
    //添加一个登录的相关属性
    var isLogin : Bool {
        //1.UserAccount的token 如果不为空 && 用户token不过期 用户已经登录
        //  没有过期  -> 过期日期(2016.4.22) 和 当前日期(2016.4.11)比较  -> 过期日期大于 当前日期
        if let u = userInfo where u.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return true
        }
        //将userAccount 设置为 nil
        userInfo = nil
        return false
    }

    private override init() {
        
        super.init()
        //用户单例
        userInfo = self.getUserInfo()
    }
    
    //MARK:使用授权码获取accesstoken
    func getAccessTocken(code:String, finished:(isSuccess:Bool)->()) {
        VIZAFNetWorkTools.shardTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil {
                //TODO:等待完善
                finished(isSuccess: false)
                print("没有获取成功")
                print(error)
                return
            }
            //TODO:等待完善
            finished(isSuccess: true)
            print("获取accesstoken成功")
            //print(result)
            //MARK: 获取用户信息
            self.getUserInfo(result!,finished: finished)


        }
        
        
        
    }
    
    //MARK: 获取用户信息
    func getUserInfo(result:AnyObject,finished:(isSuccess:Bool)->()) {
        
        guard let dict = result as? [String:AnyObject] else{
            
            //SVProgressHUD.showErrorWithStatus("数据错误")
            finished(isSuccess: false)
            return
            
        }
    
        VIZAFNetWorkTools.shardTools.getUserInfo(dict["access_token"]! as! String, uid: dict["uid"]!) { (result1, error) -> () in
            if result1 == nil {
                //SVProgressHUD.showErrorWithStatus("尼玛,又不对了")
                finished(isSuccess: false)
                return
            }
            
        
            guard var userDict = result1 as? [String : AnyObject] else{
            
                //SVProgressHUD.showErrorWithStatus("数据格式不对啊!!")
                finished(isSuccess: false)
                return
            
            }
        
            //拼接字典获得完整的用户信息
            for (k,v) in dict{
                userDict[k] = v
            }
            //print(userDict)
        
            //MARK: 保存用户信息:通过偏好设置
            self.saveUserInfo(userDict)
            //执行成功回调
            finished(isSuccess: true)
        
            //MARK:执行回调成功了以后要给单例里面的用户赋值
            self.userInfo = VIZUserInfo(dict: userDict)
        
        
        }
        
        
        
        
    }
}

//存取数据扩展
extension VIZUserViewAccountModel {
    
    //MARK:存储数据偏好设置
    func saveUserInfo(userDict:[String:AnyObject]) {
        
        //MARK: 保存用户信息:通过偏好设置
        let userDefault = NSUserDefaults.standardUserDefaults()
        //偏好设置里面不能够存有空值的字典
        //userDefault.setObject(userDict, forKey: userInfoKey)
        
        //字典转模型
        let userInfo = VIZUserInfo.init(dict: userDict)
        
        //模型转字典
        let keys = ["access_token","avatar_large","name","expires_in","uid"]
        //let accountDict = account.dictionaryWithValuesForKeys(keys)
        let userInfoDict = userInfo.dictionaryWithValuesForKeys(keys)
        
        //偏好设置存储字典
        userDefault.setObject(userInfoDict, forKey: userInfoKey)
        //同步
        userDefault.synchronize()
        //print(NSHomeDirectory())
        
        
    }
    
    //MARK:取数据偏好设置(返回对象)
    func getUserInfo()->VIZUserInfo?{
        
        guard let dict =  NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            
            return nil
        }
        
        let user = VIZUserInfo(dict: dict)
        
        return user
        
    }
    
}














